package com.hqyj.freemovie.front.interview;

/*
 * 冰箱里有100根冰棍，大林和小林放学回家后吃冰棍，多线程统计各吃了多少根。
 *
 * */

import java.util.concurrent.*;

//冰箱类
class IceBox {

    public static int iceSreamNumber = 100; //冰棍的数量；
}

class Son implements Callable<Integer> {

    private String name;

    public Son(String name) {
        this.name = name;
    }


    @Override
    public Integer call() throws Exception {
        //肯定是不停的吃冰棍
        int iCounter = 0;
        while (true) {
            String sonName = Thread.currentThread().getName();
            //给冰箱上锁。
            synchronized (IceBox.class) {
                //判断一下冰箱的冰棍是否已经吃完。
                if (IceBox.iceSreamNumber <= 0) {
                    break; //退出循环
                }

                System.out.println(this.name + "吃掉一根冰棍.....");
                IceBox.iceSreamNumber--;

                iCounter++;

                TimeUnit.MILLISECONDS.sleep(10); //休眠100毫秒
            }
        }

        return iCounter;
    }
}

public class IceScreamDemo {

    //阻塞式关闭线程池。
    public static void awaitAfterShutdown(ExecutorService threadPool) {
        threadPool.shutdown();
        try {
            if (!threadPool.awaitTermination(200, TimeUnit.SECONDS)) {
                threadPool.shutdownNow();
            }
        } catch (InterruptedException ex) {
            threadPool.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }

    public static void main(String[] args) throws Exception {

        Son bigSon = new Son("大林");
        Son smallSon = new Son("小林");
        //创建一个固定大小的线程池。
        ExecutorService executor = Executors.newFixedThreadPool(2);
        Future<Integer> bigSonFuture = executor.submit(bigSon);
        Future<Integer> smallSonFuture = executor.submit(smallSon);

        //等待线程结束。
        awaitAfterShutdown(executor);

        Integer bigSonNumber = bigSonFuture.get();
        Integer smallSonNumber = smallSonFuture.get();

        System.out.println("大林吃了：" + bigSonNumber + "根冰棍!");
        System.out.println("小林吃了：" + smallSonNumber + "根冰棍！");
    }

}
